package cn.iocoder.boot.service.impl.supplier;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.iocoder.boot.entity.ComponentPrice;
import cn.iocoder.boot.entity.ComponentStock;
import cn.iocoder.boot.enums.SupplierCodeEnum;
import cn.iocoder.boot.service.CallLimitService;
import cn.iocoder.boot.service.ComponentPriceService;
import cn.iocoder.boot.service.ComponentStockService;
import cn.iocoder.boot.service.HttpRequestLogService;
import cn.iocoder.boot.service.impl.SalePriceConfigServiceImpl;
import cn.iocoder.boot.utils.MessageUtil;
import cn.iocoder.boot.utils.tme.HttpService;
import cn.iocoder.boot.utils.tme.SignatureService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.net.URL;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
@DS("master")
@Slf4j
public class TMEServiceImpl {

    @Resource
    private ComponentStockService componentStockService;

    @Resource
    private ComponentPriceService componentPriceService;

    @Resource
    private SalePriceConfigServiceImpl salePriceConfigService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private CallLimitService callLimitService;

    @Resource
    private HttpRequestLogService httpRequestLogService;

    // API凭证常量
    private static final String USD_TOKEN = "707d350df5a71d1a7a68e4b1246469835c2386eede82222f78";
    private static final String RMB_TOKEN = "3a14f06a1699e7c893b2e5fc00e512f6be0f06afe164df3215";
    private static final String SECRET = "699b0a732926a5969153";

    // API地址常量
    private static final String API_PRODUCT_URL = "https://api.tme.eu/Products/GetProducts.json";
    private static final String API_PRICE_STOCK_URL = "https://api.tme.eu/Products/GetPricesAndStocks.json";

    // 超时时间设置(毫秒)
    private static final int HTTP_TIMEOUT = 30000;

    /**
     * 查询单个产品信息
     */
    public List<ComponentPrice> queryOne(String model, String currency, Map<String, BigDecimal> componentSupplierMap) {
        String finalToken = "USD".equals(currency) ? USD_TOKEN : RMB_TOKEN;

        try {
            // 构建请求参数
            Map<String, String> params = new TreeMap<>();
            params.put("Token", finalToken);
            params.put("SymbolList[0]", model);
            params.put("Country", "CN");
            params.put("Language", "en");

            // 调用限制检查
            callLimitService.supplierLimitCall(SupplierCodeEnum.TME.getCode());

            // 生成签名并添加到参数
            String signature = SignatureService.signature(API_PRODUCT_URL, SECRET, params);
            params.put("ApiSignature", signature);

            Map<String, Object> objectMap = new HashMap<>(params);

            // 使用Hutool发送POST请求，自动关闭资源
            try (HttpResponse response = HttpRequest.post(API_PRODUCT_URL)
                    .form(objectMap)
                    .timeout(HTTP_TIMEOUT)
                    .execute()) {
                httpRequestLogService.saveHttpRequestLog(API_PRODUCT_URL, "tme_queryOne", model, response.body(), response.getStatus());
                // 检查HTTP响应状态
                if (!response.isOk()) {
                    log.error("TME产品查询请求失败，状态码: {}", response.getStatus());
                    return new ArrayList<>();
                }

                String responseBody = response.body();
                log.info("{} TME产品 queryOne API response: {}", model, responseBody);

                // 解析响应
                JSONObject jsonResponse = JSON.parseObject(responseBody);
                String status = jsonResponse.getString("Status");

                if ("OK".equals(status)) {
                    JSONObject data = jsonResponse.getJSONObject("Data");
                    JSONArray productList = data.getJSONArray("ProductList");
                    List<ComponentStock> stockList = new ArrayList<>();
                    for (int i = 0; i < productList.size(); i++) {
                        JSONObject item = productList.getJSONObject(i);

                        // 创建并设置ComponentStock对象
                        ComponentStock stock = new ComponentStock();
                        stock.setModel(item.getString("Symbol"));
                        stock.setType(item.getString("Category"));
                        stock.setPartnumber(item.getString("Symbol"));
                        stock.setKeyword(model);

                        String photoUrl = item.getString("Photo");
                        if (photoUrl != null && !photoUrl.startsWith("http")) {
                            stock.setPicUrl("https:" + photoUrl);
                        } else {
                            stock.setPicUrl(photoUrl);
                        }

                        stock.setSpecifications(item.getString("Description"));
                        stock.setStockType(1);
                        stock.setSupplierCode(SupplierCodeEnum.TME.getCode());
                        stock.setUniqueId(SupplierCodeEnum.TME.getCode() + "_" + item.getString("Symbol"));
                        componentStockService.saveComponentStockOfUniqueKey(stock);
                        log.info("TME组件[{}]库存保存成功，ID: {}", model, stock.getId());
                        stockList.add(stock);
                    }
                    Map<String, ComponentStock> componentStockMap = stockList.stream().collect(Collectors.toMap(
                            ComponentStock::getUniqueId,
                            Function.identity(),
                            (existing, replacement) -> replacement
                    ));
                    List<ComponentPrice> componentPriceList = query(stockList, currency, componentSupplierMap);
                    componentPriceList.forEach(x -> x.setStockInfo(componentStockMap.get(x.getUniqueId())));
                    return componentPriceList;
                } else {
                    log.warn("TME产品查询状态异常: {}", status);
                    MessageUtil.sentMessage("26827", "TME产品查询型号异常" + responseBody, "TME产品查询型号异常");
                    return new ArrayList<>();
                }
            }

        } catch (Exception e) {
            log.error("查询TME产品信息失败, model: {}", model, e);
            MessageUtil.sentMessage("26827", "TME产品查询型号异常" + e.getMessage(), "TME查询型号异常");
        }
        return new ArrayList<>();
    }

    /**
     * 批量查询产品价格和库存
     */
    public List<ComponentPrice> query(List<ComponentStock> listByIds, String currency, Map<String, BigDecimal> componentSupplierMap) {
        // 1. 过滤得捷电子供应商的组件，提取型号和ID映射
        List<String> models = listByIds.stream()
                .filter(stock -> Objects.equals(stock.getSupplierCode(), SupplierCodeEnum.TME.getCode()))
                .map(ComponentStock::getPartnumber)
                .collect(Collectors.toList());

        if (CollectionUtils.isEmpty(models)) {
            log.info("无TME供应商的组件需要查询");
            return new ArrayList<>();
        }

        String finalToken = "USD".equals(currency) ? USD_TOKEN : RMB_TOKEN;

        try {
            for (String model : models) {
                // 构建请求参数
                Map<String, String> params = new TreeMap<>(); // Because we needs sorted parameters
                params.put("Token", finalToken);
                params.put("SymbolList[0]", model);
                params.put("Country", "CN");
                params.put("Language", "en");
                if (currency.equals("USD")) {
                    params.put("Currency", currency);
                }


                String signature = SignatureService.signature(API_PRICE_STOCK_URL, SECRET, params);
                params.put("ApiSignature", signature);

                String responseBody = HttpService.sendPost(new URL(API_PRICE_STOCK_URL), params);


                log.info("{} TME产品 query API response: {}", model, responseBody);

                // 解析响应
                JSONObject jsonResponse = JSON.parseObject(responseBody);
                String status = jsonResponse.getString("Status");

                if ("OK".equals(status)) {
                    JSONObject data = jsonResponse.getJSONObject("Data");
                    JSONArray productList = data.getJSONArray("ProductList");
                    List<ComponentPrice> componentPriceList = new ArrayList<>();
                    for (int i = 0; i < productList.size(); i++) {
                        JSONObject item = productList.getJSONObject(i);
                        JSONArray prices = item.getJSONArray("PriceList");

                        // 处理价格信息
                        JSONArray resultArray = new JSONArray();
                        for (int p = 0; p < prices.size(); p++) {
                            JSONObject priceItem = prices.getJSONObject(p);
                            cn.hutool.json.JSONObject priceInfo = new cn.hutool.json.JSONObject();

                            priceInfo.put("Price", priceItem.getBigDecimal("PriceValue").toString());
                            priceInfo.put("Currency", currency);
                            priceInfo.put("Quantity", priceItem.getInteger("Amount").toString());

                            resultArray.add(priceInfo);
                        }

                        // 处理销售价格配置
                        String saleJson = salePriceConfigService.getSaleJson(
                                resultArray.toJSONString(),
                                item.getString("Symbol"),
                                currency
                        );

                        ComponentPrice componentPrice = new ComponentPrice(
                                SupplierCodeEnum.TME.getCode() + "_" + model,
                                resultArray.toJSONString(),
                                item.getLong("Amount"),
                                null,
                                null,
                                currency,
                                item.getString("Symbol"),
                                resultArray.toJSONString(),
                                saleJson,
                                componentSupplierMap.getOrDefault(SupplierCodeEnum.TME.getCode(), BigDecimal.valueOf(2))
                        );

                        componentPriceService.createComponentPriceOfUniqueKey(componentPrice);
                        componentPriceList.add(componentPrice);
                    }
                    return componentPriceList;
                } else {
                    log.warn("TME产品查询状态异常: {}", status);
                    MessageUtil.sentMessage("26827", "TME产品查询型号价格失败" + responseBody, "TME产品查询型号价格失败");
                    return new ArrayList<>();
                }
            }


        } catch (Exception e) {
            log.error("查询TME产品信息失败, model: {}", models.toString(), e);
            MessageUtil.sentMessage("26827", "TME产品查询型号价格异常" + e.getMessage(), "TME查询型号价格异常");
        }
        return new ArrayList<>();
    }
}
